package com.emergency.engine.service.impl;

import com.emergency.base.domain.Scenar;
import com.emergency.common.util.CommonUtils;
import com.emergency.common.util.DateUtils;
import com.emergency.common.util.IdWorker;
import com.emergency.engine.dao.TimeLineDao;
import com.emergency.engine.domain.TimeLine;
import com.emergency.engine.service.RealService;
import com.emergency.engine.service.SchemeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

/**
 * @Author lijie
 */
@Service
public class RealServiceImpl implements RealService {

	private static final Logger logger = LoggerFactory.getLogger(SchemeService.class);

	@Autowired
	private TimeLineDao timeLineDao;


	@Autowired
	private IdWorker idWorker;

	@Autowired
	private RedisTemplate redisTemplate;

	@Override
	public boolean deductionScenar(Long scenarId, int status, int rate) {
		/**
		 * 1.先从timeline表里面查询出scenarID为scenarId是否存在，不存在表示是第一次推演，插入数据
		 * 2.如果已经存在，则更新status和rate
		 * */

		//从timeline表里面查询出scenarID为scenarId是否存在
		TimeLine timeLine=timeLineDao.findByScenarId(scenarId);

		if(CommonUtils.isNullOrEmpty(timeLine)){
            //创建时间轴对象
			timeLine=new TimeLine();
			timeLine.setId(idWorker.nextId());
			//插入场景数据
			timeLine.setScenar(new Scenar(scenarId));
			//启动开始时间
			timeLine.setStartTime(new Date());
			//设置结束时间
			timeLine.setEndTime(DateUtils.parseDate("2020-04-24 12:00:00"));
			//插入状态数据
			timeLine.setStatus(status);
			//插入进度数据初始化为0
			timeLine.setProgress(0l);

		}
		//1.若当前状态为0，推演继续
		else if(status == 0){
			//插入推演倍数数据
			timeLine.setRate(rate);
		}
		else if(status == 1){
			//2.若当前状态为1，进度停止更新
			timeLine.setStatus(status);
			//插入推演倍数数据
			timeLine.setRate(rate);
		}else{
			//3若当前状态为2，进度停止更新
			timeLine.setStatus(status);
		}
		//若继续则将当前时间进度更新到timeLine数据库
		timeLineDao.saveAndFlush(timeLine);
		//更新缓存
		flushTimes();

		return true;
	}

	//更新缓存
	private void flushTimes() {
		List<TimeLine> timeLines = (List<TimeLine>) redisTemplate.opsForValue().get("scheduled_timelines");
		//如果timelines缓存为空则查询数据库
		if(CommonUtils.isNullOrEmpty(timeLines)){
			timeLines= timeLineDao.findAllByStatus(0);
		//如果数据库中的timelines不为空则插入timelines到缓存
			if(!CommonUtils.isNullOrEmpty(timeLines)){
			redisTemplate.opsForValue().set("scheduled_timelines",timeLines);
		}
	}else {
		redisTemplate.delete("scheduled_timelines");
	}
}

	@Override
	public TimeLine getProgress(Long scenarId) {
        //查询时间进度表并返回
		TimeLine timeLine=timeLineDao.findByScenarId(scenarId);
		return timeLine;
	}

}
